﻿@using db = System.Data.Entity.Infrastructure;
@using si.caha.Model;
@using si.caha.Repository;

@{
    var msg = "";
    var disabledAttribute = "";

    // auto-admin user script - move in other file with other DB reset
    if (IsPost)
    {
        var email = "admin@caha.si";
        var password = "admin";
        var role = "admin";
        var requireToken = true;
        var dataBase = Database.Open("db");
        
        var dataContext = new DataContext();
        var userRepository = new UserRepository(dataContext);
        var categoryRepository = new CategoryRepository(dataContext);
        
        if (!userRepository.DoesUserWithEmailExists(email))
        {
            var user = new User() { Email = email };
            userRepository.Add(user);
            
            var token = WebSecurity.CreateAccount(email, password, requireToken);
            WebSecurity.ConfirmAccount(token);
            dataBase.Execute("INSERT INTO webpages_Roles (RoleName) VALUES (@0)", role);
            
            var roleId = dataBase.QueryValue("SELECT RoleId FROM webpages_Roles WHERE LOWER(RoleName) = LOWER(@0)", role);
            dataBase.Execute("INSERT INTO webpages_UsersInRoles (UserId, RoleId) VALUES (@0, @1)", 
                            WebSecurity.GetUserId(email),
                            roleId);
            
            msg += "Admin user created!";
            disabledAttribute = "disabled";
        }
        else
        {
            msg += "Admin user already exists!";
            disabledAttribute = "disabled";
        }
        
        if (categoryRepository.GetAll().Count == 0)
        {
            dataBase.Execute("INSERT INTO categories (CategoryParentId, Level, Title) VALUES (0, 0, 'Test')");
            var categoryId = dataBase.QueryValue("SELECT CategoryId FROM categories WHERE LOWER(Title) = LOWER(@0)", "Test");
            dataBase.Execute("INSERT INTO items (Title, Description, Price, CategoryId, DateAdded) VALUES ('Test item', 'Description', 10.3, @0, @1)", categoryId, System.DateTime.Now);
            
            msg += " Dummy category and item(s) created!";
            disabledAttribute = "disabled";
        }
        else
        {
            msg += " Dummy category and item(s) already exists!";
            disabledAttribute = "disabled";
        }
    }
}
<h1>Delete this file for production!</h1>
<h2>@msg</h2>
<form method="post" action="">
    <p><b>Before creating admin user webpages_Membership and other tables must exist in DB!</b></p>
    <input type="submit" value="Create admin user and fill DB with dummy data!" @disabledAttribute />
    @if (disabledAttribute != "")
    {
        <b><a href="@Href("~/")">Go home!</a></b>
    }
</form>